package com.softserveinc.autorent.controller;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.Query;

public abstract class AbstractManager<T> {

	private Class<T> entityClass;

	public Class<T> getEntityClass() {
		return entityClass;
	}

	public AbstractManager(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	protected abstract EntityManager getEntityManager();

	protected abstract void setEntityManager(EntityManager em);

	public void create(T entity) {
		getEntityManager().persist(entity);
	}

	public T read(Object id) {
		return getEntityManager().find(entityClass, id);
	}

	public void update(T entity) {
		getEntityManager().merge(entity);
	}

	public void delete(T entity) {
		if (entity != null) {
			getEntityManager().remove(entity);
		}
	}

	public void delete(int id) {
		T entity = (T) getEntityManager().find(entityClass, id);
		delete(entity);
	}

	public Collection<T> getAll() {
		final String className = entityClass.getSimpleName();
		Query q = getEntityManager().createQuery("from " + className + " c");
		Collection<T> lst = q.getResultList();
		return lst;
	}
}
